<?php

declare (strict_types=1);

namespace app\admin\controller;
use app\BaseController;
use app\admin\model\User as UserModel;
use app\common\controller\Backend;
use think\facade\Db;
use think\facade\View;

class User extends Backend
{
    public function initialize() {
        parent::initialize();
        $this->_mod  = new \app\admin\model\User();
    }

    public function _before_index(){

        $fileds = ['username','title','status'];
        $searchArr = $this->_search($fileds);
        $this->_list($this->_mod, $searchArr, 'id', 'desc');
        View::assign('searchArr', $searchArr);
    }


    public function _before_insert($data){
        if($data['password'] == ''){
            return '密码不能为空';
        }
        if($data['password'] != $data['repassword']){
            return '两次密码不一致';
        }
    }
    public function _handle_insert($data){
        unset ($data['repassword']);
        //密码加密
        $data['password'] = sha1($data['password']);
        return $data;
    }

    public function _before_add(){
        $role= Db::name('user_role')->where(array('status'=>1))->select();
        View::assign('role',$role);
    }

    public function _before_update($data){
        if($data['password'] != $data['repassword']){
            return '两次密码不一致';
        }
    }

    public function _handle_update($data){
        unset ($data['repassword']);
        if($data['password']){
            $data['password'] = sha1($data['password']);
        }else{
            unset ($data['password']);
        }
        return $data;
    }

    public function _before_edit(){
        $role= Db::name('user_role')->where(array('status'=>1))->select();
        View::assign('role',$role);
    }


    /**
     * ajax检测邮箱是否存在
     */
    public function ajax_check_email() {
        $user_mod = new UserModel();
        $name = request()->param('email');
        $id = request()->param('id');
        if ($user_mod->email_exists($name,  $id)) {
            return error(0,'该邮箱已经存在','','add');
        } else {
            return success(1,'操作成功','','add');
        }


    }
}